import {
  CLOUND_ENV
} from '/config'
const db = wx.cloud.database({
  env: CLOUND_ENV,
  traceUser: true,
})
/* 请求封装
 传入url完整链接
 datas为数据对象，不传默认为空
 type为请求的方式，分为GET POST PUT 不传默认未GET请求
 返回请求后的实例结果*/
export function re(url, datas, type) {
  return new Promise((resolve, reject) => {
    wx.cloud.callFunction({
      name: 'cloud',
      data: {
        options: Object.assign({
          url: url,
          method: type || 'GET',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
        }, datas)
      },
      success: res => {
        resolve(JSON.parse(res.result.body));
      },
      fail: err => {
        console.error(err)
        reject(err);
      }
    })
  });
}
export function dbSave(table, data) {
  /**调用云函数dbsave保存一条数据库记录
   * 参数：table，数据表的名称
   * 参数：data，包含数据表字段名-值对的对象
   * 若data._id，为空，增加记录；非空，则修改记录
   * 若更新/新增，返回row
   */
  return new Promise((resolve, reject) => {
    data._table = table
    wx.cloud.callFunction({
      name: 'dbsave',
      data: data,
      complete: res => {
        if (res.result) resolve(res.result)
        else reject(res)
      }
    })
  })
}

export function dbsave(table, data, ifShowLoadingIcon = false) {
  /**调用云函数dbsave保存一条数据库记录
   * 参数：table，数据表的名称
   * 参数：data，包含数据表字段名-值对的对象
   * 若data._id，为空，增加记录；非空，则修改记录
   * 若更新/新增，返回row
   */
  return new Promise((resolve, reject) => {
    data._table = table
    show("正在保存……", ifShowLoadingIcon)
    wx.cloud.callFunction({
      name: 'dbsave',
      data: data,
      complete: res => {
        hide(ifShowLoadingIcon)
        if (res.result) resolve(res.result)
        else reject(res)
      }
    })
  })
}

export function dbdelete(table, id, ifShowLoadingIcon = false) {
  /**调用云函数dbdelete根据_id删除记录
   * 参数：table，数据表的名称
   * 参数：id，包含_id的字符串或者数组
   * 云函数永远返回true
   */
  let data = {}
  let ids = typeof (id) == 'string' ? [id] : id
  data._table = table
  data._ids = ids
  return new Promise((resolve, reject) => {
    show("正在删除……", ifShowLoadingIcon)
    wx.cloud.callFunction({
      name: 'dbdelete',
      data: data,
      success: s => {
        resolve(s)
      },
      fail: f => {
        reject(f)
      },
      complete: c => {
        hide(ifShowLoadingIcon)
      }
    })
  })
}

export function remove_cloud_file(ids) {
  //根据id删除云文件
  //id是字符串或数组
  return new Promise((resolve, reject) => {
    if (typeof (ids) === 'string' && ids == '')
      reject(0);
    if (typeof (ids) === 'object' && array_equal(ids, []))
      reject(0);
    wx.cloud.callFunction({
      name: 'removefile',
      data: {
        ids: ids
      },
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

export function dbone(table, id, ifShowLoadingIcon = false) {
  //从table取出_id=id的一条记录
  return new Promise((resolve, reject) => {
    show("正在读取……", ifShowLoadingIcon)
    db.collection(table).doc(id).get({
      success: res => {
        resolve(res.data)
      },
      fail: err => {
        reject(err)
      },
      complete: c => {
        hide(ifShowLoadingIcon)
      }
    })
  })
}

export function dbdata(table, where = {}, order1 = [], order2 = [], order3 = [], field = [], data = []) {
  //调用dbrows，递归取值，取出所有符合条件的记录
  let skip = data.length
  return new Promise((resolve) => {
    dbrows(table, where, 20, skip, order1, order2, order3, field).then(rows => {
      if (rows.length) {
        data = data.concat(rows)
        dbdata(table, where, order1, order2, order3, field, data).then(res => resolve(res))
      } else {
        return resolve(data)
      }
    }).catch(err => {
      resolve([])
    })
  })
}

export function dball(table, where = {}, order1 = [], order2 = [], order3 = [], field = [], ifShowLoadingIcon = false) {
  //取出一个数据表的所有记录
  if (array_equal(order1, [])) order1 = ['modifytime', 'desc']
  if (array_equal(order2, [])) order2 = ['createtime', 'desc']
  if (array_equal(order3, [])) order3 = ['_id', 'desc']
  let fields = {}
  if (!array_equal(field, [])) {
    field.forEach(
      function (k) {
        fields[k] = true
      }
    )
    fields._id = true
  }
  return new Promise((resolve, reject) => {
    show("正在读取……", ifShowLoadingIcon)
    wx.cloud.callFunction({
      name: 'dball',
      data: {
        _table: table,
        _where: where,
        _order1: order1,
        _order2: order2,
        _order3: order3,
        _fields: fields
      },
      success: res => {
        resolve(res.result.data)
      },
      fail: err => {
        reject(err)
      },
      complete: c => {
        hide(ifShowLoadingIcon)
      }
    })
  })
}

export function dbrows(table, where = {}, num = 20, skip = 0, order1 = [], order2 = [], order3 = [], field = [], ifShowLoadingIcon = false) {
  /** 取出多页记录
   * table：字符串，数据表的名字
   * where：对象，形如{done:false,age:70}
   * num:每一页取出的数量，最大20
   * skip：跳过的数量
   * order1-3：排序规则
   * field:需要返回的字段，一维数组
   */
  if (array_equal(order1, [])) order1 = ['modifytime', 'desc']
  if (array_equal(order2, [])) order2 = ['createtime', 'desc']
  if (array_equal(order3, [])) order3 = ['_id', 'desc']
  let fields = {}
  if (!array_equal(field, [])) {
    field.forEach(
      function (k) {
        fields[k] = true
      }
    )
    fields._id = true
  }
  return new Promise((resolve, reject) => {
    show("正在读取……", ifShowLoadingIcon)
    db.collection(table)
      .where(where)
      .orderBy(order1[0], order1[1])
      .orderBy(order2[0], order2[1])
      .orderBy(order3[0], order3[1])
      .skip(skip)
      .limit(num)
      .field(fields)
      .get({
        success: res => {
          resolve(res.data)
        },
        fail: err => {
          reject(err)
        },
        complete: c => {
          hide(ifShowLoadingIcon)
        }
      })
  })
}

export function dbcount(table, where = {}) {
  /** 取出符合要求的记录数目
   * table：字符串，数据表的名字
   * where：对象，形如{done:false,age:70}
   */
  return new Promise((resolve, reject) => {
    db.collection(table).
    where(where).
    count({
      success: res => {
        resolve(res.total)
      },
      fail: err => {
        reject(0)
      }
    })
  })
}

function array_equal(a, b) {
  //判断两个数组是否相等
  let a1 = JSON.parse(JSON.stringify(a))
  let a2 = JSON.parse(JSON.stringify(b))
  return a1.sort().toString() == a2.sort().toString()
}

function show(title = '加载中', run = true) {
  //减少书写文字
  if (run) {
    wx.showLoading({
      title: title,
      mask: true
    })
  }
}

function hide(run = true) {
  if (run)
    wx.hideLoading()
}